package com.zhende.hr.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.HandlerInterceptor;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhende.hr.constant.Constans;
import com.zhende.hr.mapper.oaview.OutAuthDao;
import com.zhende.hr.utils.IpUtils;
import com.zhende.hr.utils.JWTUtils;

@Component
@CrossOrigin
public class OutAuthInteceptor implements HandlerInterceptor {
	
	private Logger log = LoggerFactory.getLogger(OutAuthInteceptor.class);

	@Autowired
	private OutAuthDao outAuthDao;
	
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            return true;
        }
        Map<String, Object> map = new HashMap<>();

      //获取请求头部信息
       //获取请求头中的令牌
        String token = request.getHeader("token");
        if(StringUtils.isNotBlank(token)) {
        	   try {
                   //验证令牌	
                   DecodedJWT verify = JWTUtils.verify(token);
                   // 记录请求
                   Claim  name = verify.getClaims().get("uuid");
                   Claim  type = verify.getClaims().get("type");
                   
                   

       			
                   if(Constans.auth_INTERFACE.equals(type.asString())) {
                   		// 接口请求
                   		String url = request.getRequestURI();
                   		String ip = IpUtils.getIpAddr(request);
                   		outAuthDao.saveOpeLog(name.asString(), url, ip,Constans.auth_INTERFACE);
                   		return true;
                   }
                   

       			
                   
                   map.put("msg","token类型不存在");
               } catch (SignatureVerificationException e){
//                   e.printStackTrace();
                   map.put("msg","无效签名");
               } catch (TokenExpiredException e){
//                   e.printStackTrace();
                   map.put("msg","token过期");
               } catch (AlgorithmMismatchException e){
//                   e.printStackTrace();
                   map.put("msg","token算法不一致");
               } catch (Exception e){
                   e.printStackTrace();
                   map.put("msg",e.toString());
               }
        }else {
        	map.put("msg","head中需要添加token");
        }
     
        map.put("state","flase");
        map.put("code",-1);
        //将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }

    public void doResponse(HttpServletResponse response,String info) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        PrintWriter writer = response.getWriter();
        ResponseEntity<String> responseEntity=new ResponseEntity<>(info, HttpStatus.NOT_ACCEPTABLE);
        String json = JSON.toJSONString(responseEntity);
        writer.write(json);
        writer.flush();
        writer.close();
    }
}
